import React from "react";
import { hot } from "react-hot-loader/root";
import { QueryRouter } from "@/utils/Router";
import { Tabs } from "./Tabs";
import styles from "./App.less";

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.defTabVal = "Popular";
    this.routeUrl = /(\?tab=)?/gi;
    this.queryRouter = new QueryRouter(true);
    this.state = {
      currTabVal: this.defTabVal,
      loadTab: null,
      query: null,
      tabList: [
        { val: "Popular", text: "Popular" },
        { val: "Battle", text: "Battle" },
      ],
      currPage: null,
    };
    this.tabPages = {
      // Popular: () => Promise.resolve(Popular),
      Popular: async () =>
        (await import(/* webpackChunkName: "Popular" */ "@/components/Popular"))
          .default,
      Battle: async () =>
        (await import(/* webpackChunkName: "Battle" */ "@/components/Battle"))
          .default,
    };
  }

  componentDidMount() {
    this.queryRouter.onRoute(this.routeUrl, this.onPageRoute);
    this.queryRouter.initRouter();
  }

  componentWillUnmount() {
    this.queryRouter.offRoute(this.routeUrl, this.onPageRoute);
  }

  onPageRoute = (url, query) => {
    const tabVal = query?.tab ?? this.defTabVal;
    this.setState({ query });
    this.loadPage(tabVal);
  };

  onTabClick = async (tabVal) => {
    this.loadPage(tabVal);
    this.queryRouter.routeUrl(`/?tab=${tabVal}`);
  };

  onRouteUrlQuery = (query) => {
    this.queryRouter.routeAppQuery(query);
  };

  loadPage = async (tabVal) => {
    this.setState({
      loadTab: tabVal,
    });
    const loadFn = this.tabPages[tabVal];
    const page = await loadFn();
    this.setState({
      loadTab: null,
      currTabVal: tabVal,
      currPage: page,
    });
  };

  render() {
    const {
      loadTab,
      currTabVal,
      tabList,
      currPage: CurrPage,
      query,
    } = this.state;
    return (
      <div>
        <Tabs
          onTabClick={this.onTabClick}
          currentVal={currTabVal}
          list={tabList}
          loadTab={loadTab}
          className={styles.tab}
        />
        <div>
          {!!CurrPage && (
            <CurrPage query={query} onRouteUrlQuery={this.onRouteUrlQuery} />
          )}
        </div>
      </div>
    );
  }
}

export default hot(App);
